package main

import (
	"fmt"
	// "time"
	"os"
	"sync"
)

/*
	异步写入数据 --> 文件
*/

var (
	wg sync.WaitGroup
)

func WriteToChan(ch chan<- string) {
	defer wg.Done()
	for i := 0; ; i++ {

		ch <- "golang " + fmt.Sprintf("%d", i) + "\n"
	}
}
func WriteToFile(ch <-chan string) {
	defer wg.Done()

	f, err := os.OpenFile("result.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()

	for {
		str := <-ch
		f.WriteString(str)
	}
}

func main() {
	ch := make(chan string, 10)
	wg.Add(4)

	go WriteToChan(ch)
	go WriteToFile(ch)
	go WriteToFile(ch)
	go WriteToFile(ch)
	go WriteToFile(ch)

	wg.Wait()
}
